import os from 'os';
import path, { resolve } from 'path';

import { isWindows } from '@ohos/hvigor';
import fse from 'fs-extra';

import { HVIGOR_USER_HOME_DIR_NAME } from './project-builder/models/constants';

class CommonConfig {

  /**
   * 当前代码所在盘符
   *
   * @type {string}
   */
  public readonly root: string;

  /**
   * ohpm 安装命令
   * @type {string}
   */
  public readonly ohpmInstallCommand: string;

  /**
   * workplace
   *
   * @type {string}
   */
  public readonly workplace: string;

  public readonly hvigorUserHome: string;

  constructor() {
    if (isWindows()) {
      this.root = __dirname.split('\\')[0];
      this.ohpmInstallCommand = 'ohpm install --all';
    } else {
      this.root = os.homedir();
      const ohpmHome = process.env.OHPM_HOME;
      this.ohpmInstallCommand = ohpmHome ? `${resolve(ohpmHome, 'bin', 'ohpm')} install --all` : 'ohpm install --all';
    }
    const packagesPath = path.join(__dirname, '../', '../', '../', '../');

    // 初始化user home路径
    const defaultUserHome = path.resolve(os.homedir(), HVIGOR_USER_HOME_DIR_NAME);
    const hvigorUserHomeEnv = process.env.HVIGOR_USER_HOME;
    this.hvigorUserHome = defaultUserHome;
    if (hvigorUserHomeEnv !== undefined && path.isAbsolute(hvigorUserHomeEnv)) {
      this.hvigorUserHome = hvigorUserHomeEnv;
      fse.ensureDirSync(this.hvigorUserHome);
    }

    this.workplace = path.join(packagesPath, '../');
  }

  /**
   * 通过当前时间生成时间字符串
   *
   * @return {string}
   */
  public createDataStr(): string {
    const date = new Date(); // 创建一个Date对象
    return date.toLocaleString('zh-CN', { // 调用toLocaleString方法，指定语言为中文
      year: 'numeric', // 年份为数字
      month: '2-digit', // 月份为数字
      day: '2-digit', // 日为数字
      hour: '2-digit', // 小时为数字
      minute: '2-digit', // 分钟为数字
      second: undefined, // 秒为数字
      hour12: false // 使用12小时制
    }).replace(/[\\/\s:]/g, '_');
  }
}

export const commonConfig: CommonConfig = new CommonConfig();
